#!/bin/python
# -*- coding: utf8 -*-


from lib.common.aliyun_ots import cli, Condition, INF_MIN, INF_MAX
import lib.common.func as com_func
import lib.common.aliyun_redis

ots = cli()
redis = lib.common.aliyun_redis.cli()

TABLE = '${table_name}'


def add_${table_name}(${key_first}, ${key_second} ,${key_third},${key_fourth},attr={}):
    ts = lib.common.func.get_ts()
    pk = {
        '${key_first}': ${type_first}(${key_first}),
        '${key_second}': ${type_second}(${key_second}),
        '${key_third}': ${type_third}(${key_third}),
        '${key_fourth}':${type_fourth}(${key_fourth}),
    }
    attr['ctime'] = ts
    attr['mtime'] = ts
    code = ots.put_row(TABLE, Condition('EXPECT_NOT_EXIST'), pk, attr)
    return code


def update_${table_name}(${key_first}, ${key_second},${key_third}, ${key_fourth},attr={}):
    ts = lib.common.func.get_ts()
    pk = {
        '${key_first}': ${type_first}(${key_first}),
        '${key_second}': ${type_second}(${key_second}),
        '${key_third}': ${type_third}(${key_third}),
        '${key_fourth}':${type_fourth}(${key_fourth}),
    }
    attr['mtime'] = ts
    code = ots.update_row(TABLE, Condition('EXPECT_EXIST'), pk, {'put': attr})
    return code


def delete_${table_name}(${key_first}, ${key_second},${key_third},${key_fourth}):
    pk = {
        '${key_first}': ${type_first}(${key_first}),
        '${key_second}': ${type_second}(${key_second}),
        '${key_third}': ${type_third}(${key_third}),
        '${key_fourth}':${type_fourth}(${key_fourth}),
    }
    code = ots.delete_row(TABLE, Condition('IGNORE'), pk)
    return code


def get_${table_name}_list_ots(${key_first}):
    pk_b = {
        '${key_first}': ${type_first}(${key_first}),
        '${key_second}': INF_MIN,
        '${key_third}':INF_MIN,
        '${key_fourth}':INF_MIN,
    }
    pk_e = {
        '${key_first}': ${type_first}(${key_first}),
        '${key_second}': INF_MAX,
        '${key_third}':INF_MAX,
        '${key_fourth}':INF_MAX,
    }
    data_list = []
    while pk_b is not None:
        rows, pk_b = ots.get_range(TABLE, 'FORWARD', pk_b, pk_e, [])
        if len(rows) > 0:
            data_list.extend(rows)
    return data_list


def get_all_${table_name}_list():
    pk_b = {
        '${key_first}': INF_MIN,
        '${key_second}': INF_MIN,
        '${key_third}':INF_MIN,
        '${key_fourth}':INF_MIN,
    }
    pk_e = {
        '${key_first}': INF_MAX,
        '${key_second}': INF_MAX,
        '${key_third}':INF_MAX,
        '${key_fourth}':INF_MAX,
    }
    data_list = []
    while pk_b is not None:
        rows, pk_b = ots.get_range(TABLE, 'FORWARD', pk_b, pk_e, [])
        if len(rows) > 0:
            data_list.extend(rows)
    return data_list
